package com.itboye.ihomebank;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.Poi;
import com.baidu.location.service.LocationService;
import com.itboye.ihomebank.adapter.HomeAdapter;
import com.itboye.ihomebank.adapter.SouSuoAdapter;
import com.itboye.ihomebank.base.BaseFragment;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.HouseBean;
import com.itboye.ihomebank.bean.HouseListBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.choosecity.CityListActivity;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.controller.LoginController;
import com.itboye.ihomebank.custom.CarouselView;
import com.itboye.ihomebank.custom.MyListView;
import com.itboye.ihomebank.custom.XScrollView;
import com.itboye.ihomebank.home.ActivityHotSouSuo;
import com.itboye.ihomebank.home.ActivityShaiXuan;
import com.itboye.ihomebank.homefragment.HouseDetailActivity;
import com.itboye.ihomebank.me.ActivityFaBuHouse;
import com.itboye.ihomebank.myzhujia.ActivityMySign;
import com.itboye.ihomebank.myzhujia.ActivityRepair;
import com.itboye.ihomebank.presenter.HousePresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;

/**
 * 首页
 * 
 */
public class HomeFragment extends BaseFragment implements OnClickListener,
		Observer {
	private CarouselView banner_top;
	private XScrollView home_scrollView;
	private MyListView home_listview;
	private EditText edit_txt;
	private ArrayList<HouseBean> arrayListHouse = new ArrayList<HouseBean>();
	HousePresenter housePresenter;
	RelativeLayout home_city;// 切换城市
	RelativeLayout home_sousuo;// 搜索
	TextView tvcity;
	// 智能门锁，签约，预约，求租
	LinearLayout include_01, include_02, include_03, include_04;
	// 维修服务，一键缴费，家政服务，签证旅游
	RelativeLayout include_weixiu, include_jiaofei, include_jiazheng,
			include_qianzheng;

	private HomeAdapter adapter;
	SouSuoAdapter souSuoAdapter;
	protected String city;
	private LocationService locationService;
	protected double lat;
	protected double lng;
	protected float radius;
	TextView textView2;

	@Override
	public int initView() {

		return R.layout.fragment_home;
	}

	private void initLocation() {
		// TODO Auto-generated method stub
		// -----------location config ------------
		locationService = ((MyApplcation) getActivity().getApplication()).locationService;
		// 获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
		locationService.registerListener(myListener);
		// 注册监听
		locationService.setLocationOption(locationService
				.getDefaultLocationClientOption());
		locationService.start();// 定位SDK
	}

	@Override
	public void onMyActivityCreated() {
		housePresenter = new HousePresenter(this);
		housePresenter.queryHouse("330100", "", "", "", "", "", "", "", "", "",
				"", "", "", "5", "");
		home_listview = (MyListView) getView().findViewById(R.id.mylistview);

		home_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(),
						HouseDetailActivity.class);
				intent.putExtra("lng", lng);
				intent.putExtra("lat", lat);
				intent.putExtra("radius", radius);
				intent.putExtra("house_no", houseListBean.getData().get(position).getHouseNo());
				startActivity(intent);
			}
		});

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

	}

	private void getListViewData() {
		

		String c = (String) SPUtils.get(getActivity(), null,
				SPContants.SELECT_CITY, "");
		if (c == "") {
			tvcity.setText("定位中..");
		} else {
			tvcity.setText(c);
		}
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		initLocation();
	}

	public void onClick(View arg0) {
		Intent intent = null;
		switch (arg0.getId()) {
		case R.id.home_city:// 切换城市
			intent = new Intent(MyApplcation.ctx, CityListActivity.class);
			startActivity(intent);
			break;
		case R.id.home_sousuo:// 搜索
			intent = new Intent(MyApplcation.ctx, ActivityHotSouSuo.class);
			startActivity(intent);
			break;
		case R.id.include_01:// 发布
			intent = new Intent(MyApplcation.ctx, ActivityFaBuHouse.class);
			startActivity(intent);
			break;
		case R.id.include_02:// 我的预约
			LoginController.onMyAppointmentClick(getActivity(), null);
			break;
		case R.id.include_03:// 我的签约
			LoginController.onMySignClick(getActivity(), null);
			break;
		case R.id.include_04:// 求租
			intent = new Intent(getActivity(), ActivityShaiXuan.class);
			startActivity(intent);
			break;
		case R.id.include_weixiu:// 住家维修
			intent = new Intent(getActivity(), ActivityRepair.class);
			startActivity(intent);
			break;
		case R.id.include_jiaofei:// 一键缴费
			housePresenter.queryHouse("330100", "", "", "", "", "", "", "", "", "",
					"", "", "", "", "");
			break;
		case R.id.include_jiazheng:// 家政服务

			break;
		case R.id.include_qianzheng:// 签约旅行

			break;
		case R.id.textView2:
			//
			StringRequest request = new StringRequest(
					"http://api.ihomebank.com/public/index.php",
					new Listener<String>() {

						@Override
						public void onResponse(String arg0) {
							// TODO Auto-generated method stub
							System.out.println("<><>" + arg0);
						}
					}, new ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError arg0) {
							// TODO Auto-generated method stub

							System.out.println("<><>0"
									+ arg0.getLocalizedMessage());
						}
					});
			MyApplcation.addRequest(request);
			break;
		default:
			break;
		}
	}

	public BDLocationListener myListener = new BDLocationListener() {
		@Override
		public void onReceiveLocation(BDLocation location) {
			StringBuffer sb = new StringBuffer(256);
			if (null != location
					&& location.getLocType() != BDLocation.TypeServerError) {
				sb.append("time : ");
				/**
				 * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
				 * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
				 */
				sb.append(location.getTime());
				sb.append("\nlocType : ");// 定位类型
				sb.append(location.getLocType());
				sb.append("\nlocType description : ");// *****对应的定位类型说明*****
				sb.append(location.getLocTypeDescription());
				sb.append("\nlatitude : ");// 纬度
				sb.append(location.getLatitude());
				lat = location.getLatitude();
				sb.append("\nlontitude : ");// 经度
				sb.append(location.getLongitude());
				lng = location.getLongitude();
				sb.append("\nradius : ");// 半径
				sb.append(location.getRadius());
				radius = location.getRadius();
				sb.append("\nCountryCode : ");// 国家码
				sb.append(location.getCountryCode());
				sb.append("\nCountry : ");// 国家名称
				sb.append(location.getCountry());
				sb.append("\ncitycode : ");// 城市编码
				sb.append(location.getCityCode());
				// cityCode=location.getCityCode();
				// cityCode=location.getCityCode();
				location.getCityCode();
				sb.append("\ncity : ");// 城市
				city = location.getCity();
				SPUtils.put(getActivity(), null, SPContants.SELECT_CITY, city);
				// tvcity.setText(city);
				sb.append(location.getCity());
				SPUtils.put(getActivity(), null, SPContants.SELECT_CITY,
						location.getCity());
				sb.append("\nDistrict : ");// 区
				sb.append(location.getDistrict());
				SPUtils.put(getActivity(), null, SPContants.SELECT_AREA,
						location.getDistrict());
				// tvLocation.setText(location.getCity() +
				// location.getDistrict());
				sb.append("\nStreet : ");// 街道
				sb.append(location.getStreet());
				sb.append("\naddr : ");// 地址信息
				sb.append(location.getAddrStr());
				sb.append("\nUserIndoorState: ");// *****返回用户室内外判断结果*****
				sb.append(location.getUserIndoorState());
				sb.append("\nDirection(not all devices have value): ");
				sb.append(location.getDirection());// 方向
				sb.append("\nlocationdescribe: ");
				sb.append(location.getLocationDescribe());// 位置语义化信息
				sb.append("\nPoi: ");// POI信息
				if (location.getPoiList() != null
						&& !location.getPoiList().isEmpty()) {
					for (int i = 0; i < location.getPoiList().size(); i++) {
						Poi poi = (Poi) location.getPoiList().get(i);
						sb.append(poi.getName() + ";");
					}
				}
				if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
					sb.append("\nspeed : ");
					sb.append(location.getSpeed());// 速度 单位：km/h
					sb.append("\nsatellite : ");
					sb.append(location.getSatelliteNumber());// 卫星数目
					sb.append("\nheight : ");
					sb.append(location.getAltitude());// 海拔高度 单位：米
					sb.append("\ngps status : ");
					sb.append(location.getGpsAccuracyStatus());// *****gps质量判断*****
					sb.append("\ndescribe : ");
					sb.append("gps定位成功");
				} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
					// 运营商信息
					if (location.hasAltitude()) {// *****如果有海拔高度*****
						sb.append("\nheight : ");
						sb.append(location.getAltitude());// 单位：米
					}
					sb.append("\noperationers : ");// 运营商信息
					sb.append(location.getOperators());
					sb.append("\ndescribe : ");
					sb.append("网络定位成功");
				} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
					sb.append("\ndescribe : ");
					sb.append("离线定位成功，离线定位结果也是有效的");
				} else if (location.getLocType() == BDLocation.TypeServerError) {
					sb.append("\ndescribe : ");
					sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
				} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
					sb.append("\ndescribe : ");
					sb.append("网络不同导致定位失败，请检查网络是否通畅");
				} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
					sb.append("\ndescribe : ");
					sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
				}
			}

			System.out.println("BaiduLocationApiDem" + sb.toString());
			// MyLocationData locData = new MyLocationData.Builder()
			// .accuracy(location.getRadius())
			// // 此处设置开发者获取到的方向信息，顺时针0-360
			// .direction(100).latitude(location.getLatitude())
			// .longitude(location.getLongitude()).build();
			// baiduMap.setMyLocationData(locData); // 设置定位数据
			// LatLng ll = new LatLng(location.getLatitude(),
			// location.getLongitude());
			// MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(ll, 16);
			// // 设置地图中心点以及缩放级别
			// // MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
			// baiduMap.animateMapStatus(u);
		}
	};

	private HouseListBean houseListBean;
	private RelativeLayout one;

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		ByAlert.alert(entity.getData());
		if (entity != null) {
			if (entity.getEventType() == HousePresenter.queryHouse_success) {
				houseListBean = (HouseListBean) entity.getData();
				if (houseListBean == null) {
					// no_data.setVisibility(View.VISIBLE);
					// sousuo_listview.setVisibility(View.GONE);
					return;
				}
				if (houseListBean.getData().size() <= 0) {
					// no_data.setVisibility(View.VISIBLE);
					// sousuo_listview.setVisibility(View.GONE);
					return;
				}
				// no_data.setVisibility(View.GONE);
				// sousuo_listview.setVisibility(View.VISIBLE);
				getListViewData();
				adapter = new HomeAdapter(getActivity(), houseListBean.getData());
				home_listview.setAdapter(adapter);
				for (int i = 0; i < 10; i++) {
					HouseBean bean = new HouseBean();
					arrayListHouse.add(bean);
				}
				adapter.notifyDataSetChanged();
//				souSuoAdapter = new SouSuoAdapter(getActivity(),
//						houseListBean.getData(), R.layout.item_sousuo);
//				home_listview.setAdapter(adapter);
			}
			one.setFocusable(true);
			one.setFocusableInTouchMode(true);
			one.requestFocus();
			home_scrollView.smoothScrollTo(0, 0);
		}

	}
}
